package cn.itcast.controller;


import cn.itcast.mapper.RoomMapper;
import cn.itcast.DTO.OrderDTO;
import cn.itcast.DTO.PageQueryDTO;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.Result;
import cn.itcast.entity.Room;
import cn.itcast.service.RoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@Slf4j
@RequestMapping("/room")
public class RoomController {
    @Autowired
    private RoomService roomService;
    @Autowired
    private RoomMapper roomMapper;

    //1.条件分页查询
    @GetMapping("/page")
    public Result<PageResult> page(PageQueryDTO dto) {
        // 调用房间服务的分页查询方法
        PageResult pageResult = roomService.page(dto);
        // 返回分页查询结果
        return Result.success(pageResult);
    }

    //2.新增房间
    @PostMapping("")
    public Result insert(@RequestBody Room room) {
        // 检查房间号是否已存在
        Room byId = roomMapper.find(room.getNumber());
        if (byId == null) {
            // 新增房间
            roomService.insert(room);
            return Result.success();
        }
           return Result.error("房间号已存在");
    }

    //3.删除房间信息
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        roomService.delete(id);
        return Result.success();
    }

    //4.根据id查询房间信息
    @GetMapping("/id")
    public Result<Room> findById(Long id) {
        Room room = roomService.findById(id);
        return Result.success(room);
    }

    //5.修改房间信息
    @PutMapping
    public Result updateRoom(@RequestBody Room room) {
        roomService.update(room);
        return Result.success();
    }

    //6.查询所有
    @GetMapping("/selectAll")
    public Result selectAll() {
        return Result.success(roomService.selectAll());
    }

    //7.根据房间号返回id
    @GetMapping("/{roomNo}")
    public Result<Integer> findIdByRoomNo(@PathVariable String roomNo) {
        log.info("roomNo{}", roomNo);
        Integer id = roomService.findIdByRoomNo(roomNo);
        return Result.success(id);
    }

    //8.根据id返回订单信息
    @GetMapping("/order/user/{id}")
    public Result<OrderDTO> findOrderById(@PathVariable Long id) {
        OrderDTO order = roomService.findOrderById(id);
        return Result.success(order);
    }
}
